K was doable working from bottom up and picking the largest set of values among node's children, then merging the other ones into it while tracking differences. Since this way every subsequent insertion that a given leaf value undergoes takes place in at least two times larger set than the previous one, we bound the number of insertions to O(log m) per leaf, for a total of O(n + m log^2 m) with std::set.
